#!/bin/bash

# shellcheck source=meta-facebook/recipes-fb/obmc_functions/files/fb-common-functions
source /usr/libexec/fb-common-functions
# shellcheck source=meta-facebook/meta-harma/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd

MESSAGE=$1
ARG=$2
VAL=$3

# remove prefix from 0_reset-cause-platrst to reset-cause-platrst
loginfo="${MESSAGE#*_}"

# get gpio chip id
number="${MESSAGE%%_*}"

# get assert or deassert message
action=$(echo "$MESSAGE" | awk '{print $NF}')

gpio_msg="${VAL#*_}"

check_valid_sgpio
valid_sgpio=$?

if [ "$valid_sgpio" -eq 0 ] || [ "$number" -ne 2 ] || [ "$action" == "assert" ]; then
    # This delay ensures the BMC does not receive abnormal events
    # during CMM/MB AC cycling or tray unplugging.
    # Such actions can cause the CPLD to lose power before the BMC,
    # leading to abnormal events being received.
    sleep 2
    busctl call \
    xyz.openbmc_project.Logging /xyz/openbmc_project/logging \
    xyz.openbmc_project.Logging.Create Create "ssa{ss}" "$loginfo" \
    xyz.openbmc_project.Logging.Entry.Level.Error 1 "$ARG" "$gpio_msg"
fi
